<?php

require_once WP_PLUGIN_DIR . '/diapucp-events/defines.php' ;

class dia_pucp_events_edit_manager {
    //adds the methods required to manipulate the framework

    public function dia_pucp_events_edit_manager(){
        add_action( 'manage_posts_custom_column', array( &$this, 'events_custom_columns' ) );
        add_action( 'load-edit.php', array( &$this, 'edit_event_load' ) );

        add_filter( 'manage_edit-event_columns', array( &$this, 'events_columns' ) );
        add_filter( 'manage_edit-event_sortable_columns', array( &$this, 'event_sortable_columns') );
    }

    public function events_columns($columns) {
	$columns = array(
		'cb' => '<input type=checkbox />',
		'title' => __( 'Events' ),
                'localization' => __( 'Where?' ),
		'startdate' => __( 'Starts' ),
                'enddate' => __( 'Ends' ),
		//'comments' => __( 'Comments' )
                'comments'  => '<img src="http://laconia.ring.pucp.edu.pe/kelvin/web/wordpress/wp-admin/images/comment-grey-bubble.png" alt="Comments">'
	);
	return $columns;
    }

    public function events_custom_columns($column)
    {
	global $post;
	if ("ID" == $column) echo $post->ID;
	elseif ('localization' == $column) echo get_post_meta($post->ID, DPEM . 'localization',true);
        elseif ('startdate' == $column) echo get_post_meta($post->ID, DPEM . 'startdate', true);
	elseif ('enddate' == $column) echo get_post_meta($post->ID, DPEM . 'enddate', true);
        elseif ('comments' == $column) echo $post->comments;
    }

    public function edit_event_load() {
	add_filter( 'request', array( &$this, 'sort_events') );
    }

    public function sort_events( $vars ) {
        if ( isset( $vars['post_type'] ) && 'event' == $vars['post_type'] ) {
            if ( isset( $vars['orderby'] ) && 'localization' == $vars['orderby'] ) {
                $vars = array_merge($vars, array(
                                'meta_key' => 'dp_em_localization',
                                'orderby' => 'meta_value'
                        ));
            }
            if ( isset( $vars['orderby'] ) && 'startdate' == $vars['orderby'] ) {
                $vars = array_merge($vars, array(
                                'meta_key' => 'dp_em_startdate',
                                'orderby' => 'meta_value'
                        ));
            }
            if ( isset( $vars['orderby'] ) && 'enddate' == $vars['orderby'] ) {
                $vars = array_merge($vars, array(
                                'meta_key' => 'dp_em_enddate',
                                'orderby' => 'meta_value'
                        ));
            }
        }
        return $vars;
    }

    public function event_sortable_columns( $columns ) {
            $columns['localization'] = 'localization';
            $columns['startdate'] = 'startdate';
            $columns['enddate'] = 'enddate';

            return $columns;
    }
}

new dia_pucp_events_edit_manager();

?>
